package com.atguigu.flink0922.chapter08;

import com.atguigu.flink0922.bean.HotItem;
import com.atguigu.flink0922.bean.UserBehavior;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.ArrayList;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/3/8 14:40
 */
public class Flink02_High_Project_HotItem {
    public static void main(String[] args) {
        
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);
        
        // 创建WatermarkStrategy
        WatermarkStrategy<UserBehavior> wms = WatermarkStrategy.<UserBehavior>forBoundedOutOfOrderness(
            Duration.ofSeconds(5)).withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>() {
            @Override
            public long extractTimestamp(UserBehavior element, long recordTimestamp) {
                return element.getTimestamp() * 1000L;
            }
        });
        
        env
            .readTextFile("input/UserBehavior.csv")
            .map(line -> { // 对数据切割, 然后封装到POJO中
                String[] split = line.split(",");
                return new UserBehavior(Long.valueOf(split[0]), Long.valueOf(split[1]), Integer.valueOf(split[2]), split[3],
                                        Long.valueOf(split[4]));
            })
            .assignTimestampsAndWatermarks(wms)  // 添加Watermark
            .filter(data -> "pv".equals(data.getBehavior()))
            .keyBy(UserBehavior::getItemId)
            .window(SlidingEventTimeWindows.of(Time.hours(1), Time.minutes(5)))
            .aggregate(
                new AggregateFunction<UserBehavior, Long, Long>() {
                    @Override
                    public Long createAccumulator() {
                        return 0L;
                    }
                    
                    @Override
                    public Long add(UserBehavior value, Long accumulator) {
                        return accumulator + 1L;
                    }
                    
                    @Override
                    public Long getResult(Long accumulator) {
                        return accumulator;
                    }
                    
                    @Override
                    public Long merge(Long a, Long b) {
                        return a + b;
                    }
                },
                new ProcessWindowFunction<Long, HotItem, Long, TimeWindow>() {
                    @Override
                    public void process(Long key,
                                        Context context,
                                        Iterable<Long> elements,
                                        Collector<HotItem> out) throws Exception {
                        out.collect(new HotItem(key, elements.iterator().next(), context.window().getEnd()));
                    }
                }
            )
            .keyBy(HotItem::getWindowEndTime)
            .process(new KeyedProcessFunction<Long, HotItem, String>() {
                // 定时器触发时间 的状态
                private ValueState<Long> timerTsState;
                private ListState<HotItem> hotItemState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    hotItemState = getRuntimeContext()
                        .getListState(new ListStateDescriptor<HotItem>("hotItemState", HotItem.class));
                    
                    timerTsState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<Long>("timerTsState", Long.class));
                }
                
                @Override
                public void processElement(HotItem value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    // 假设[0,5)窗口来一条放入的状态, 定义定时器, 在 5+1秒之后触发排序
                    hotItemState.add(value);
                    
                    // 什么时间定义定时器
                    if (timerTsState.value() == null) { // [0,5)这个窗口内数据第一次到这里
                        // 注册定时器
                        Long timerTs = value.getWindowEndTime() + 1000L;
                        ctx.timerService().registerEventTimeTimer(timerTs);
                        // 更新定时器的触发时间的状态
                        timerTsState.update(timerTs);
                    }
                }
                
                @Override
                public void onTimer(long timestamp,
                                    OnTimerContext ctx,
                                    Collector<String> out) throws Exception {
                    
                    final ArrayList<HotItem> hotItems = new ArrayList<>();
                    
                    for (HotItem hotItem : hotItemState.get()) {
                        hotItems.add(hotItem);
                    }
                    hotItems.sort((o1, o2) -> o2.getCount().compareTo(o1.getCount()));
                    
                    final StringBuilder sb = new StringBuilder();
                    sb.append("-------------------------\n");
                    sb.append("窗口结束时间: ").append(timestamp - 1000).append("\n");
                    for (int i = 0; i < Math.min(hotItems.size(), 3); i++) {
                        sb.append(hotItems.get(i)).append("\n");
                    }
                    out.collect(sb.toString());
                    
                    //清除状态, 节省内存
                    timerTsState.clear();
                    hotItemState.clear();
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
